package processor

import "gitee.com/baizhige/mongong-go/util/arrays"

func Register(typer string, processor Processor) {
	processorMap[typer] = append(processorMap[typer], processor)
}

func Get(typer string, obj any) []Processor {
	return arrays.FilterCopy(processorMap[typer], func(process Processor) bool {
		return process.Match(obj)
	})
}

// ProcessOne 任意步骤的处理器返回nil时  都会结束
func ProcessOne(typer string, obj any) (res any) {
	processors := Get(typer, obj)
	res = obj
	for _, processor := range processors {
		if res == nil {
			return
		}
		res = processor.Process(res)
	}
	return
}

// ProcessMany 为了提高批量处理的性能 并不会对每个元素都match 仅仅对泛型T 的零值进行赋值
// 当某个元素 经过process后成为nil 则丢弃
func ProcessMany[T any](typer string, objs []T) (res []any) {
	res = make([]any, len(objs))
	if len(objs) == 0 {
		return
	}
	var t T
	processors := Get(typer, t)
	for _, item := range objs {
		var currObj any = item
		for _, processor := range processors {
			if currObj == nil {
				break
			}
			currObj = processor.Process(currObj)
		}
		if currObj != nil {
			res = append(res, currObj)
		}
	}
	return
}
